package top.yongyan0624.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.web.bind.annotation.*;

import top.yongyan0624.common.lang.Result;
import top.yongyan0624.entity.Goods;
import top.yongyan0624.entity.StoreCart;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-09-14
 */
@RestController
@RequestMapping("/store/cart")
public class StoreCartController extends BaseController {
    @PostMapping("/modify")
    public Result modify(@RequestBody StoreCart cart) {

        HashMap<String, Long> map = new HashMap<>();
        map.put("user_id", cart.getUserId());
        map.put("goods_id", cart.getGoodsId());

        storeCartService.saveOrUpdate(cart, new UpdateWrapper<StoreCart>().allEq(map));

        Goods goods = goodsService.getById(cart.getGoodsId());

        goods.setUser(sysUserService.getById(goods.getUserId()));
        goods.setImgList(StrUtil.split(goods.getImg(), ',' ,true,true));

        cart.setGoods(goods);

        return Result.success(cart);
    }

    @GetMapping("/show/{id}")
    public Result show(@PathVariable("id") Long userId) {
        List<StoreCart> cartList = storeCartService.list(new QueryWrapper<StoreCart>().eq("user_id", userId).gt("amount", 0));

        cartList.forEach(c -> {
            Goods goods = goodsService.getById(c.getGoodsId());

            goods.setUser(sysUserService.getById(goods.getUserId()));
            goods.setImgList(StrUtil.split(goods.getImg(), ',' ,true,true));

            c.setGoods(goods);
        });

        return Result.success(cartList);
    }
}
